package com.wowangz.cms.dailyoperation.storechannel.api;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import sun.misc.BASE64Encoder;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.dailyoperation.store.pojo.StoreEntity;
import com.wowangz.cms.dailyoperation.store.service.StoreService;
import com.wowangz.cms.dailyoperation.storechannel.pojo.StoreChannel;
import com.wowangz.cms.dailyoperation.storechannel.service.StoreChannelService;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.utils.DesUtil;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.RSAUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;

@SuppressWarnings({ "restriction", "deprecation" })
@Scope("prototype")
@Controller
public class StoreChannelController extends BaseController{
	
	private static Logger logger = LoggerFactory.getLogger(StoreChannelController.class);

	private static String filename = "secretfile";
	
	/**
	 * 点击菜单"商户通道"显示“商户通道”列表
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/storechannel/list.web")
	public String queryStoreChannelList(HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "/WEB-INF/jsp/dailyoperation/storechannel/storeChannelList";
	}
	
	/**
	 * 打开“商户通道”列表加载列表数据
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/dailyoperation/storechannel/queryStoreChannelListInfoDataGrid.json")
	public void queryStoreChannelListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {

		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);
			String storeid = request.getParameter("storeid");
			if (StringUtils.isNotEmpty(storeid)) {
				map.put("storeid", Long.parseLong(storeid));
			}
			StoreChannelService storeChannelService = (StoreChannelService) IssTransactionContainer.getInstance(StoreChannelService.class, false);
			long resultCount = storeChannelService.findResultCount(map);
			List<StoreChannel> resultList = storeChannelService.findResultList(map);
			StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
			for(StoreChannel result:resultList){ 
				  	Long storeID = result.getStoreid();
				  	StoreEntity store = storeService.findOne(storeID);//根据商户ID获取商户实体类
		            result.setStorename(store.getName());
		            result.setStorenumber(store.getNumber());
		    }   

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("storenumber", DataTypeConstant.STRING);
			dataStyle.addDepict("storename", DataTypeConstant.STRING);
			dataStyle.addDepict("url", DataTypeConstant.STRING);
			dataStyle.addDepict("secretkey", DataTypeConstant.STRING);
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 进入商户通道新增
	 */
	@RequestMapping(value = "/dailyoperation/storechannel/toAddChannel.web", method = RequestMethod.GET)
	public String toAddChannel(HttpServletRequest request, HttpServletResponse response, Model model) {
		try{
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return "/WEB-INF/jsp/dailyoperation/storechannel/storeChannelAdd";
	}
	
	/**
	 * 新增商户通道
	 */
	@RequestMapping(value = "/dailyoperation/storechannel/addChannel.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String addChannel(HttpServletRequest request, HttpServletResponse response, Model model) {
		StoreChannel storeChannel = null;
		try {
			storeChannel = (StoreChannel) ServletUtils.getParametersToBaseEntity(request, StoreChannel.class);
			//add by yoyo 截取掉连接最后多余的斜杠
			storeChannel.setUrl(storeChannel.getUrl().replace("/+\\Z", ""));
			storeChannel.setInputtime(new Date());
			storeChannel.setInputuserid(userContext.getLoginUser().getId());
			storeChannel.setModifytime(new Date());
			storeChannel.setModifyuserid(userContext.getLoginUser().getId());
			storeChannel.setStatusid(SysConstant.RecordStatus.VALID);
			StoreChannelService storeChannelService = (StoreChannelService) IssTransactionContainer.getInstance(StoreChannelService.class, true);			
			storeChannelService.addChannel(storeChannel);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);//注释后，保存成功的信息会出来，但是保存后再点击返回，依然会出现保存成功的信息
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert2"));
		}
		return "/WEB-INF/jsp/dailyoperation/storechannel/storeChannelList";
	}
	/**
	 * 验证商户通道（url，secretkey，storeid）
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/dailyoperation/storechannel/validattionChannel.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void validationChannel(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			StoreChannel storeChannel = null;
			StringBuffer errorMsg = new StringBuffer();
			HashMap<String, Object> map = new HashMap<String, Object>();
			storeChannel = (StoreChannel) ServletUtils.getParametersToBaseEntity(request, StoreChannel.class);
			
			//add by yoyo 截取掉连接最后多余的斜杠
			storeChannel.setUrl(storeChannel.getUrl().replace("/+\\Z", ""));
			StoreChannelService storeChannelService = (StoreChannelService) IssTransactionContainer.getInstance(StoreChannelService.class, false);
			map.put("statusid", SysConstant.RecordStatus.VALID);
			if(null != storeChannel.getId()){
				map.put("id", storeChannel.getId());
			}
			if(null == storeChannel.getStoreid()){//如果没有从放大镜选值
				getUserContext().setErrorMessage(MessageResourcesUtils.getMessage(request, "dailyoperation.storeChannel.add.storeselect"));
			}else{
				map.put("url", storeChannel.getUrl());
				if(!storeChannelService.validationChannel(map)){
					errorMsg.append(MessageResourcesUtils.getMessage(request, "dailyoperation.storeChannel.add.urlexist"));
				}
				map.remove("url");
				map.put("secretkey", storeChannel.getSecretkey());
				if(!storeChannelService.validationChannel(map)){
					errorMsg.append(MessageResourcesUtils.getMessage(request, "dailyoperation.storeChannel.add.secretkeyexist"));
				}
				map.remove("secretkey");
				map.put("storeid", storeChannel.getStoreid());
				if(!storeChannelService.validationChannel(map)){
					errorMsg.append(MessageResourcesUtils.getMessage(request, "dailyoperation.storeChannel.add.storeexist"));
				}
				map.remove("storeid");
			}
	
			if(StringUtils.isNotEmpty(errorMsg.toString())){
				userContext.setErrorMessage(errorMsg.toString());
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 进入商户通道修改
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/storechannel/toUpdateChannel.web")
	public String toUpdateChannel(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String channelId = getRequest().getParameter("id");
			StoreChannelService storeChannelService = (StoreChannelService) IssTransactionContainer.getInstance(StoreChannelService.class, false);
			StoreChannel storeChannel = storeChannelService.findChannelById(channelId);
			StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
			StoreEntity storeEntity = storeService.findOne(storeChannel.getStoreid());
			storeChannel.setStorename(storeEntity.getName());
			storeChannel.setStorenumber(storeEntity.getNumber());
			model.addAttribute("storeChannel", storeChannel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/dailyoperation/storechannel/storeChannelUpdate";
	}
	
	/**
	 * 修改商户通道
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/storechannel/updateChannel.web", method = { RequestMethod.GET, RequestMethod.POST })
	public String updateChannel(HttpServletRequest request, HttpServletResponse response, Model model) {
		StoreChannel storeChannel = null;
		try {
			storeChannel = (StoreChannel) ServletUtils.getParametersToBaseEntity(request, StoreChannel.class);
			//add by yoyo 截取掉连接最后多余的斜杠
			storeChannel.setUrl(storeChannel.getUrl().replace("/+\\Z", ""));
			storeChannel.setModifytime(new Date());
			storeChannel.setModifyuserid(userContext.getLoginUser().getId());
			StoreChannelService storeChannelService = (StoreChannelService) IssTransactionContainer.getInstance(StoreChannelService.class, true);		
			storeChannelService.updateChannel(storeChannel);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert6"));
			userContext.setCloseWindow(true);//注释后，保存成功的信息会出来，但是保存后再点击返回，依然会出现保存成功的信息
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert7"));
		}
		return "/WEB-INF/jsp/dailyoperation/storechannel/storeChannelList";
	}
	
	/**
	 * 删除商户通道
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/dailyoperation/storechannel/deleteChannel.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deleteChannel(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			Long channelId = Long.valueOf(getRequest().getParameter("id"));
			StoreChannel storeChannel = new StoreChannel();
			storeChannel.setId(channelId);
			storeChannel.setStatusid(SysConstant.RecordStatus.INVALID);
			StoreChannelService storeChannelService = (StoreChannelService) IssTransactionContainer.getInstance(StoreChannelService.class, true);
			storeChannelService.updateChannel(storeChannel);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert4"));
		}
	}
	
	/**
	 * 进入商户通道查看
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/dailyoperation/storechannel/toViewChannel.web")
	public String toViewChannel(HttpServletRequest request, HttpServletResponse response, Model model) {
		try {
			String channelId = getRequest().getParameter("id");
			StoreChannelService storeChannelService = (StoreChannelService) IssTransactionContainer.getInstance(StoreChannelService.class, false);
			StoreChannel storeChannel = storeChannelService.findChannelById(channelId);
			StoreService storeService = (StoreService) IssTransactionContainer.getInstance(StoreService.class, false);
			StoreEntity storeEntity = storeService.findOne(storeChannel.getStoreid());
			storeChannel.setStorename(storeEntity.getName());
			storeChannel.setStorenumber(storeEntity.getNumber());
			model.addAttribute("storeChannel", storeChannel);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/WEB-INF/jsp/dailyoperation/storechannel/storeChannelView";
	}
	
	
	/**
	 * 生成密钥
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/dailyoperation/storechannel/createSecretKey.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void createSecretKey(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			HashMap<String, Object> map = RSAUtils.getKeys();  
	        //生成公钥和私钥  
	        RSAPublicKey rsaPublicKey = (RSAPublicKey) map.get("public");
	        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) map.get("private");
	        String publickey = "modulus="+rsaPublicKey.getModulus().toString() + ";" + "exponent=" + rsaPublicKey.getPublicExponent().toString();
	        String privatekey= "modulus="+rsaPrivateKey.getModulus().toString() + ";" + "exponent=" + rsaPrivateKey.getPrivateExponent().toString();
	        String secretkey = RSAUtils.getRandomString(24);
	        ajaxDataEntity.getMap().put("publickey", publickey);
	        ajaxDataEntity.getMap().put("privatekey", privatekey);
	        ajaxDataEntity.getMap().put("secretkey", secretkey);
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 导出密钥
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/dailyoperation/storechannel/exportSecretKey.web", method = { RequestMethod.GET, RequestMethod.POST })
	public void exportSecretKey(HttpServletRequest request, HttpServletResponse response, Model model) {
		InputStream fis = null;
		OutputStream toClient = null;
		try {
			String channelId = getRequest().getParameter("id");
			StoreChannelService storeChannelService = (StoreChannelService) IssTransactionContainer.getInstance(StoreChannelService.class, false);
			StoreChannel storeChannel = storeChannelService.findChannelById(channelId);
			File file = new File(filename);
			this.createFile(file);
			String content = storeChannel.getPublickey() + ";3deskey=" + storeChannel.getSecretkey();
			//对密钥进行加密
			BASE64Encoder encoder = new BASE64Encoder();
			content  = encoder.encode(DesUtil.encryptMode(SysConstant.DESKEY.DESKEY.getBytes(), content.getBytes()));
			this.writeTxtFile(content, file);

			fis = new BufferedInputStream(new FileInputStream(file));

			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);

			response.reset();
			response.addHeader("Content-Disposition", "attachment;filename=" + filename);
			response.addHeader("Content-Length", "" + file.length());

			toClient = new BufferedOutputStream(response.getOutputStream());

			response.setContentType("application/octet-stream");

			toClient.write(buffer);

			toClient.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try{
				if(fis!=null)
					fis.close();
				if(toClient!=null)
					toClient.close();
			}catch(Exception e)
			{
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 创建文件
	 * 
	 * @param fileName
	 * @return
	 */
	private boolean createFile(File fileName) throws Exception {
		boolean flag = false;
		try {
			if (!fileName.exists()) {
				fileName.createNewFile();
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	} 
	
	/**
	 * 写入内容
	 * @param content
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public boolean writeTxtFile(String content, File fileName)
			throws Exception {
		RandomAccessFile mm = null;
		boolean flag = false;
		FileOutputStream o = null;
		try {
			o = new FileOutputStream(fileName);
			o.write(content.getBytes("UTF-8"));
			o.close();
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try{
				if (mm != null) {
					mm.close();
				}
			}catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		return flag;
	}
	
	
	
	/**
	 * 测试连接是否成功
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "resource", "unused" })
	@RequestMapping(value = "/dailyoperation/storechannel/testCommonlist.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void testCommonlist(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		String str_url = request.getParameter("url");
		
		HttpClient httpclient = new DefaultHttpClient();
		//设置连接超时时间为5000毫秒
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); 
		HttpGet httpget = new HttpGet(str_url);
		// 若连接成功，会得到404的状态码
		// 反之，连接不上会抛出 java.net.ConnectException: Connection timed out: connect错误
		try {
			HttpResponse httpResponse = httpclient.execute(httpget);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(
					request, "dailyoperation.storeChannel.list.alert1"));
		} catch (ClientProtocolException e) {
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(
					request, "dailyoperation.storeChannel.list.alert2"));
			e.printStackTrace();
		} catch (IOException e) {
			userContext.setErrorMessage(MessageResourcesUtils.getMessage(
					request, "dailyoperation.storeChannel.list.alert2"));
			e.printStackTrace();
		} finally
		{
			if (httpclient != null) {
				httpclient.getConnectionManager().shutdown();
			}
		}
		
		try {
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
